package com.example.demo;

import java.io.*;
import java.nio.channels.FileChannel;

/**
 * 切割大文件的三种方式
 * RandomAccessFile
 * BufferedInputStream
 * FileChannel
 */
public class BigFileDemo {

    public static void splitFile(String filePath, long chunkSize) throws IOException {
        try (RandomAccessFile inputFile = new RandomAccessFile(filePath, "r")) {
            long fileSize = inputFile.length();
            // Math.ceil向上取整，1.2 -> 2
            int numChunks = (int) Math.ceil((double) fileSize / chunkSize);

            for (int i = 0; i < numChunks; i++) {
                int bufferSize = (int) Math.min(chunkSize, fileSize - i * chunkSize);
                byte[] buffer = new byte[bufferSize];
                inputFile.seek(i * chunkSize);
                int bytesRead = inputFile.read(buffer);
                // 处理分割后的数据，例如写入到新文件中
            }
        }
    }

    public static void splitFile2(String filePath, long chunkSize) throws IOException {
        try (BufferedInputStream inputFile = new BufferedInputStream(new FileInputStream(filePath))) {
            long fileSize = new File(filePath).length();
            int numChunks = (int) Math.ceil((double) fileSize / chunkSize);

            for (int i = 0; i < numChunks; i++) {
                int bufferSize = (int) Math.min(chunkSize, fileSize - i * chunkSize);
                byte[] buffer = new byte[bufferSize];
                int bytesRead = inputFile.read(buffer);
                // 处理分割后的数据，例如写入到新文件中
            }
        }
    }

    public static void splitFile3(String filePath, long chunkSize) throws IOException {
        try (FileChannel inputFileChannel = new FileInputStream(filePath).getChannel()) {
            long fileSize = inputFileChannel.size();
            int numChunks = (int) Math.ceil((double) fileSize / chunkSize);

            for (int i = 0; i < numChunks; i++) {
                long position = i * chunkSize;
                long count = Math.min(chunkSize, fileSize - position);
                try (FileChannel outputFileChannel = new FileOutputStream("Chunk" + i).getChannel()) {
                    inputFileChannel.transferTo(position, count, outputFileChannel);
                }
            }
        }
    }
}
